neutron.setTitle("Tasks")
neutron.setMinSize(280, 340)
neutron.getInfo((data) => {
    if (data[0]["h"] < 340) {
        neutron.setWinSize(280, 340)
    }
});

if (window.parent.window.NEUTRON_TASKS_OPENED == true) {
    neutron.close()
} else {
    window.parent.window.NEUTRON_TASKS_OPENED = true
    neutron.onClose(() => {
        window.parent.window.NEUTRON_TASKS_OPENED = false
        neutron.close()
    })
}

var ws = undefined

task_status = {
    "running": "运行",
    "success": "成功",
    "failed": "失败",
    "stop": "停止"
}

function create_task_obj(json_body) { // 创建任务的 dom
    if (json_body.data.status == "running") { // 更新按钮内容
        var template_stopbutton_text = "停止"
        var template_stopbutton_callback = "stop_job(" + json_body.id + ")"
    } else {
        var template_stopbutton_text = "删除"
        var template_stopbutton_callback = "remove_job(" + json_body.id + ")"
    }
    var buttons_tmpl_string = ""
    if (json_body.data.buttons.length != 0) {
        for (var i = 0; i < json_body.data.buttons.length; i++) {
            buttons_tmpl_string += `<button class="task_action_btn" onclick="run_button(` + json_body.id + `,` + i + `)">` + json_body.data.buttons[i] + `</button>`
        }
        var display_style = "flex"
    } else {
        // var display_style = "none"
        var display_style = "flex"
    }
    var template = `
    <div class="task_type" id="task_type-`+ json_body.id + `">
        <span class="task_title">`+ json_body.data.name + `</span>
        <span class="task_info">`+ json_body.data.description + `</span>
        <span class="task_log" style="display:none;">`+ json_body.data.log.replace(/\n/g, "<br>").replace(/ /g, "&nbsp;") + `</span>
        <div class="task_progress"><div class="task_progress_len" style="width:`+ json_body.data.progress + `%"></div></div>
        <div class="task_status task_status_`+ json_body.data.status + `">` + task_status[json_body.data.status] + `</div>
        <button class="task_stop" onclick="`+ template_stopbutton_callback + `">` + template_stopbutton_text + `</button>
        <button class="task_logbtn" onclick="show_log(` + json_body.id + `)">日志</button>
        <div class="task_action" style="display:`+ display_style + `">` +
        buttons_tmpl_string + `
        </div>
    </div>`
    document.getElementById("root").insertAdjacentHTML("afterbegin", template)
}
function update_task_obj(json_body) { // 更新任务 dom
    if (json_body.data.status == "running") {
        var template_stopbutton_text = "停止"
        var template_stopbutton_callback = "stop_job(" + json_body.id + ")"
    } else {
        var template_stopbutton_text = "删除"
        var template_stopbutton_callback = "remove_job(" + json_body.id + ")"
    }
    var buttons_tmpl_string = ""
    if (json_body.data.buttons.length != 0) {
        for (var i = 0; i < json_body.data.buttons.length; i++) {
            buttons_tmpl_string += `<button class="task_action_btn" onclick="run_button(` + json_body.id + `,` + i + `)">` + json_body.data.buttons[i] + `</button>`
        }
        if (document.getElementById("task_type-" + json_body.id).getElementsByClassName("task_log")[0].style.display == "none") {
            document.getElementById("task_type-" + json_body.id).getElementsByClassName("task_log")[0].style.display = "block"
        }
        // root_obj.getElementsByClassName("task_action")[0].style.display = "block"
    } else {
        // root_obj.getElementsByClassName("task_action")[0].style.display = "none"
    }
    var root_obj = document.getElementById("task_type-" + json_body.id)
    if (root_obj == undefined) {
        return
    }
    root_obj.getElementsByClassName("task_title")[0].innerHTML = json_body.data.name
    root_obj.getElementsByClassName("task_info")[0].innerHTML = json_body.data.description
    root_obj.getElementsByClassName("task_log")[0].innerHTML = json_body.data.log.replace(/\n/g, "<br>").replace(/ /g, "&nbsp;")
    root_obj.getElementsByClassName("task_status")[0].innerHTML = task_status[json_body.data.status]
    root_obj.getElementsByClassName("task_progress_len")[0].style.width = json_body.data.progress + "%"
    root_obj.getElementsByClassName("task_status")[0].className = "task_status task_status_" + json_body.data.status
    root_obj.getElementsByClassName("task_stop")[0].innerHTML = template_stopbutton_text
    root_obj.getElementsByClassName("task_stop")[0].setAttribute("onclick", template_stopbutton_callback)
    root_obj.getElementsByClassName("task_action")[0].innerHTML = buttons_tmpl_string
}
function stop_job(id) { // 停止任务
    ws.send(
        JSON.stringify({
            "type": "stop",
            "data": {
                "id": id
            }
        })
    )
}
function remove_job(id) { // 删除任务
    ws.send(
        JSON.stringify({
            "type": "remove",
            "data": {
                "id": id
            }
        })
    )
}
function show_log(id) { // 切换 log 现在状态
    if (document.getElementById("task_type-" + id).getElementsByClassName("task_log")[0].style.display == "none") {
        document.getElementById("task_type-" + id).getElementsByClassName("task_log")[0].style.display = "block"
    } else {
        document.getElementById("task_type-" + id).getElementsByClassName("task_log")[0].style.display = "none"
    }
}
function run_button(id, btnid) { // 选择按钮
    ws.send(
        JSON.stringify({
            "type": "button",
            "data": {
                "id": id,
                "data": btnid
            }
        })
    )
}
window.onload = function () {
    var link = API_PATH + "/tasks"
    var showall = new URLSearchParams(window.location.search).get("showall") // 显示所有用户的任务
    if (showall == "true") {
        // 校验在服务端，普通用户不会打开这个页面
        link += "?show_all=true"
    }
    ws = new WebSocket(link); // 链接
    ws.onmessage = function (event) {
        var data = JSON.parse(event.data);
        setTimeout(() => {
            if (data.type == "init") { // 初始化
                for (var key in data.data) {
                    create_task_obj({
                        "id": key,
                        "data": data.data[key]
                    })
                }
            } else if (data.type == "add") {
                create_task_obj(data.data)
            } else if (data.type == "update") {
                update_task_obj(data.data)
            } else if (data.type == "remove") {
                document.getElementById("task_type-" + data.data.id).outerHTML = ""
            }
        }, 20)
    }

}